package jxd.myDwr;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.directwebremoting.dwrp.Batch;

import cn.util.Common;

public class PlainCallMarshaller extends BaseCallMarshaller
{
  private boolean allowScriptTagRemoting = false;

  private String scriptTagProtection = "throw 'allowScriptTagRemoting is false.';";
  protected String getOutboundMimeType()
  {
    return "text/javascript";
  }

  protected void sendOutboundScriptPrefix(PrintWriter out, String batchId)
    throws IOException
  {
    if (!this.allowScriptTagRemoting)
    {
      synchronized (out)
      {
        out.println(this.scriptTagProtection);
      }
    }
  }

  protected void sendOutboundScriptSuffix(PrintWriter out, String batchId)
    throws IOException
  {
  }

  protected void sendScript(PrintWriter out, String script)
    throws IOException
  {
    synchronized (out)
    {
      out.println(script);
    }
  }
  public void marshallException(HttpServletRequest request, HttpServletResponse response, Exception ex)
  throws IOException
	{
	  response.setContentType(getOutboundMimeType());
	  PrintWriter out = response.getWriter();
	  Batch batch = (Batch)request.getAttribute("org.directwebremoting.dwrp.batch");
	  String batchId;
	  if ((batch != null) && (batch.getCalls() != null))
	  {
	    batchId = batch.getCalls().getBatchId();
	  }
	  else
	  {
	    batchId = null;
	  }
	
	  sendOutboundScriptPrefix(out, batchId);
	  String script = EnginePrivate.getRemoteHandleBatchExceptionScript(batchId, ex);
	  out.print(script);
	  sendOutboundScriptSuffix(out, batchId);
	}
  public void setAllowScriptTagRemoting(boolean allowScriptTagRemoting)
  {
    this.allowScriptTagRemoting = allowScriptTagRemoting;
  }

  public void setScriptTagProtection(String scriptTagProtection)
  {
    this.scriptTagProtection = scriptTagProtection;
  }

	public void marshallException(HttpServletRequest request,
			HttpServletResponse response, String mes) throws IOException {
	  response.setContentType(getOutboundMimeType());
	  //PrintWriter out = response.getWriter();
	  Batch batch = (Batch)request.getAttribute("org.directwebremoting.dwrp.batch");
	  String batchId;
	  if ((batch != null) && (batch.getCalls() != null))
	  {
	    batchId = batch.getCalls().getBatchId();
	  }
	  else
	  {
	    batchId = null;
	  }
	
	  //sendOutboundScriptPrefix(out, batchId);
	  String script = EnginePrivate.getRemoteHandleLoginScript(batchId, mes);
	  //out.print(script);
	  //sendOutboundScriptSuffix(out, batchId);
	  Common.flushScript(request,response,script);
	}
}